package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.UserService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        log.info("开始统计营业额数据: begin={}, end={}", begin, end);
        
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        
        // 使用统一的字符串转换方法
        String dateListStr = StringUtils.collectionToCommaDelimitedString(dateList);
        String turnoverListStr = StringUtils.collectionToCommaDelimitedString(turnoverList.stream().map(String::valueOf).collect(Collectors.toList()));
        
        log.info("营业额统计数据结果: dateList={}, turnoverList={}", dateListStr, turnoverListStr);

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(dateListStr)
                .turnoverList(turnoverListStr)
                .build();
    }


    /**
     * 根据时间区间统计订单数量
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end){
        log.info("开始统计订单数据: begin={}, end={}", begin, end);
        
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的总订单数 select count(id) from orders where order_time > ? and order_time < ?
            Integer orderCount = getOrderCount(beginTime, endTime, null);

            //查询每天的有效订单数 select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).orElse(0);
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).orElse(0);
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        
        // 使用统一的字符串转换方法
        String dateListStr = StringUtils.collectionToCommaDelimitedString(dateList);
        String orderCountListStr = StringUtils.collectionToCommaDelimitedString(orderCountList.stream().map(String::valueOf).collect(Collectors.toList()));
        String validOrderCountListStr = StringUtils.collectionToCommaDelimitedString(validOrderCountList.stream().map(String::valueOf).collect(Collectors.toList()));
        
        log.info("订单统计数据结果: dateList={}, orderCountList={}, validOrderCountList={}, totalOrderCount={}, validOrderCount={}, orderCompletionRate={}", 
                dateListStr, orderCountListStr, validOrderCountListStr, totalOrderCount, validOrderCount, orderCompletionRate);

        return OrderReportVO.builder()
                .dateList(dateListStr)
                .orderCountList(orderCountListStr)
                .validOrderCountList(validOrderCountListStr)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        log.info("开始统计用户数据: begin={}, end={}", begin, end);
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer newUser = getUserCount(beginTime, endTime);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser = getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        // 使用StringUtils.collectionToCommaDelimitedString保持一致性
        String dateListStr = StringUtils.collectionToCommaDelimitedString(dateList);
        String newUserListStr = StringUtils.collectionToCommaDelimitedString(newUserList.stream().map(String::valueOf).collect(Collectors.toList()));
        String totalUserListStr = StringUtils.collectionToCommaDelimitedString(totalUserList.stream().map(String::valueOf).collect(Collectors.toList()));

        return UserReportVO.builder()
                .dateList(dateListStr)
                .newUserList(newUserListStr)
                .totalUserList(totalUserListStr)
                .build();

    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        log.info("开始统计销量排名top10数据: begin={}, end={}", begin, end);
        
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        log.info("查询时间范围: beginTime={}, endTime={}", beginTime, endTime);
        
        // 先尝试查询所有时间范围的数据，看是否有数据返回
        List<GoodsSalesDTO> allTimeData = orderMapper.getSalesTop10(null, null);
        log.info("所有时间范围的数据数量: {}", allTimeData != null ? allTimeData.size() : 0);
        
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);
        
        // 添加调试日志
        log.info("查询到的销量top10数据数量: {}", goodsSalesDTOList != null ? goodsSalesDTOList.size() : 0);
        if (goodsSalesDTOList != null) {
            log.debug("查询到的销量top10数据详情: goodsSalesDTOList={}", goodsSalesDTOList);
        }
        
        // 处理空列表情况
        if (goodsSalesDTOList == null || goodsSalesDTOList.isEmpty()) {
            log.info("销量排名top10数据为空，返回空结果");
            // 即使没有数据，也返回格式正确的空结果
            return SalesTop10ReportVO.builder()
                    .nameList("")  // 确保返回空字符串而不是null
                    .numberList("")  // 确保返回空字符串而不是null
                    .build();
        }

        // 使用统一的字符串转换方法，替换已弃用的StringUtils.join
        String nameList = StringUtils.collectionToCommaDelimitedString(
            goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()));
        String numberList = StringUtils.collectionToCommaDelimitedString(
            goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).map(String::valueOf).collect(Collectors.toList()));

        log.info("销量排名top10数据结果: nameList={}, numberList={}", nameList, numberList);

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }


    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        // 只有当beginTime不为null时才添加到查询条件中
        if (beginTime != null) {
            map.put("begin", beginTime);
        }
        // 只有当endTime不为null时才添加到查询条件中
        if (endTime != null) {
            map.put("end", endTime);
        }
        return userMapper.countByMap(map);
    }

    /**
     * 根据时间区间统计指定状态的订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        // 只有当status不为null时才添加到查询条件中
        if (status != null) {
            map.put("status", status);
        }
        // 只有当beginTime不为null时才添加到查询条件中
        if (beginTime != null) {
            map.put("begin", beginTime);
        }
        // 只有当endTime不为null时才添加到查询条件中
        if (endTime != null) {
            map.put("end", endTime);
        }
        log.debug("查询订单数量参数: status={}, begin={}, end={}", status, beginTime, endTime);
        
        Integer result = orderMapper.countByMap(map);
        log.debug("查询订单数量结果: {}", result);
        return result;
    }
}